package deploy

import (
	"app/daos"
	_ "app/env"
	"app/utils"
	"github.com/fwhezfwhez/errorx"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

var ormS = daos.OrmS

func InitDB() {
	//初始化表结构
	for _, v := range ormS {
		if err := daos.GetConnection().AutoMigrate(v); err != nil {
			logrus.Error(errorx.Wrap(err), v)
		}
	}

	insertInitData()
	logrus.Info("database initialize finish")
}

//插入初始化数据

func insertInitData() {
	var userModel = daos.Admin{Username: "root", Nickname: "管理员", Password: utils.HashPassword("123456"), IsAdmin: 1}
	if err := daos.GetConnection().Where("username = ?", "root").Take(&userModel).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			if err = daos.GetConnection().Debug().Create(&userModel).Error; err != nil {
				logrus.Fatal(errorx.Wrap(err))
			}

			logrus.Println("insert init data")
			return
		}

		logrus.Fatal(errorx.Wrap(err))
	}
}
